package com.huanzhidadi.logaspect.config;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.*;
import com.alibaba.fastjson2.JSON;
import com.huanzhidadi.logaspect.aspect.ThirdLogAspect;
import com.huanzhidadi.logaspect.model.ThirdLogDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
public class HutoolHttpUtilConfig {
    @Autowired
    public void HutoolHttpUtilConfig() {
        // 设置hutool HttpUtil的request请求参数
        GlobalInterceptor.INSTANCE.addRequestInterceptor(httpRequest -> this.wirteRequestLog(httpRequest));
        // 设置hutool HttpUtil的response参数
        GlobalInterceptor.INSTANCE.addResponseInterceptor(httpResponse -> this.writeResponseLog(httpResponse));
        // 设置hutool HttpUtil的连接超时时间、读取响应超时时间
        HttpGlobalConfig.setTimeout(3000);
    }

    private void wirteRequestLog(HttpRequest request){
        log.info("HutoolHttpUtilConfig wirteRequestLog");
        String reqUrl = request.getUrl();
        log.info("reqUrl: {}", reqUrl);
        Method method = request.getMethod();
        String reqType = method.name();
        log.info("reqType: {}", reqType);

        ThirdLogDO thirdLogDO = ThirdLogAspect.thirdLogThreadLocal.get();
        // 无ThirdLogAnno注解标识的方法不进行日志落库
        if (Objects.isNull(thirdLogDO)) {
            return;
        }
        thirdLogDO.setReqTime(new Date());
        thirdLogDO.setReqUrl(reqUrl);
        thirdLogDO.setReqType(reqType);
        if ("POST".equalsIgnoreCase(reqType)) {
            if (null != request.bodyBytes()) {
                String bodyStr = new String(request.bodyBytes());
                log.info("body: {}", bodyStr);
                thirdLogDO.setBodyParam(bodyStr);
            }
        } else if ("GET".equalsIgnoreCase(reqType)) {
            Map<String, Object> form = request.form();
            if (CollUtil.isNotEmpty(form)) {
                String formStr = JSON.toJSONString(form);
                log.info("formStr: {}", formStr);
                thirdLogDO.setFormParam(formStr);
            }
        }
        ThirdLogAspect.thirdLogThreadLocal.set(thirdLogDO);
    }

    private void writeResponseLog(HttpResponse response){
        log.info("HutoolHttpUtilConfig writeResponseLog");
        ThirdLogDO thirdLogDO = ThirdLogAspect.thirdLogThreadLocal.get();
        // 无ThirdLogAnno注解标识的方法不进行日志落库
        if (Objects.isNull(thirdLogDO)) {
            return;
        }
        // 执行耗时
        Long runningTime = System.currentTimeMillis() - thirdLogDO.getReqTime().getTime();
        log.info("执行耗时: {}", runningTime);
        thirdLogDO.setReqCost(runningTime);
        if (null != response) {
            String responseBody = response.body();
            thirdLogDO.setResult(responseBody);
        }
        ThirdLogAspect.thirdLogThreadLocal.set(thirdLogDO);
    }

}
